import jsonServer from "json-server";
import path from "path";
import cors from "cors";
import { Request, Response, NextFunction } from "express";

const server = jsonServer.create();
const router = jsonServer.router(path.join(__dirname, "../data/db.json"));
const middlewares = jsonServer.defaults();

// 添加 token 验证中间件
// 添加类型定义
type JsonServerMiddleware = (
  req: Request,
  res: Response,
  next: NextFunction
) => void;

// 修改 token 验证中间件的类型
const authMiddleware: JsonServerMiddleware = (req, res, next) => {
  const publicPaths = ["/api/auth/login"];

  if (publicPaths.includes(req.path)) {
    return next();
  }

  const bearerToken = req.headers.authorization;

  if (!bearerToken) {
    return res.status(401).json({
      code: 401,
      success: false,
      data: null,
      message: "未登录或 token 已过期",
    });
  }

  // 支持 Bearer token 格式
  const token = bearerToken.startsWith("Bearer ")
    ? bearerToken.slice(7)
    : bearerToken;

  if (!token.startsWith("mock_token_")) {
    return res.status(401).json({
      code: 401,
      success: false,
      data: null,
      message: "无效的 token",
    });
  }

  next();
};

// 应用中间件
server.use(cors());
server.use(middlewares);
server.use(jsonServer.bodyParser);
server.use(authMiddleware); // 使用类型断言

// 修复登录接口的类型
server.post("/api/auth/login", (req: Request, res: Response) => {
  const { username, password } = req.body;
  const db: any = router.db.getState();
  const user = db.users.find(
    (u: any) => u.username === username && u.password === password
  );

  if (user) {
    res.json({
      code: 0,
      success: true,
      data: {
        token: "mock_token_" + Date.now(),
        user: {
          id: user.id,
          username: user.username,
          name: user.name,
          email: user.email,
          avatar: user.avatar,
        },
      },
      message: "success",
    });
  } else {
    res.status(401).json({
      code: 401,
      success: false,
      data: null,
      message: "用户名或密码错误",
    });
  }
});

// 添加获取用户信息接口
// 修改获取用户信息接口
server.get("/api/auth/profile", (req: Request, res: Response) => {
  const token = req.headers.authorization;

  if (!token) {
    res.status(401).json({
      code: 401,
      success: false,
      data: null,
      message: "未登录",
    });
    return;
  }

  // 返回用户信息时包含头像
  res.json({
    code: 0,
    success: true,
    data: {
      id: "1",
      username: "admin",
      name: "管理员",
      email: "admin@example.com",
      avatar:
        "https://gw.alipayobjects.com/zos/rmsportal/BiazfanxmamNRoxxVxka.png",
    },
    message: "success",
  });
});

// 请求处理中间件
const requestHandler = (req: Request, res: Response, next: NextFunction) => {
  if (req.method === "POST") {
    const now = new Date().toISOString();
    req.body = {
      ...req.body,
      createdAt: now,
      updatedAt: now,
    };
  }

  if (req.method === "PUT") {
    req.body = {
      ...req.body,
      updatedAt: new Date().toISOString(),
    };
  }

  next();
};

// 响应格式化中间件
const responseHandler = (req: Request, res: Response, next: NextFunction) => {
  const originalSend = res.send;
  res.send = function (body) {
    try {
      const data = JSON.parse(body);
      const response = {
        code: res.statusCode === 200 ? 0 : res.statusCode,
        success: res.statusCode === 200,
        data,
        message: res.statusCode === 200 ? "success" : "error",
      };
      return originalSend.call(this, JSON.stringify(response));
    } catch (e) {
      return originalSend.call(this, body);
    }
  };
  next();
};

// 错误处理中间件
const errorHandler = (
  err: Error,
  req: Request,
  res: Response,
  next: NextFunction
) => {
  res.status(500).json({
    code: 500,
    success: false,
    message: err.message || "服务器内部错误",
    data: null,
  });
};

// 最后应用通用路由和错误处理
server.use(requestHandler);
server.use(responseHandler);
server.use("/api", router);
server.use(errorHandler);

const port = process.env.PORT || 3002;
server.listen(port, () => {
  console.log(`JSON Server is running on port ${port}`);
});
